﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace Simhopp.Common
{
    public static class DiverMap
    {
        public static int SaveDiverToDatabase(Diver diver)
        {
            diver.CredentialsId = CredentialsMap.SaveCredentialsToDatabase(diver.Credentials);
            var id = GenericMap.SaveObjectToDatabase(diver);
            foreach (var dive in diver.Dives)
                DiveMap.SaveDiveToDatabase(dive);
            return id;
        }

        public static void SaveDiversToDatabase(List<Diver> divers)
        {
            foreach (var diver in divers)
                SaveDiverToDatabase(diver);
            MyLogger.Debug("All divers saved to database");
        }

        public static List<Diver> ReadAllDiversFromDatabase()
        {
            var dictionary = GenericMap.ReadAllObjectsFromDatabase(typeof(Diver));
            try
            {
                var divers = dictionary.Select(Diver.GetFromDictionary).ToList();
                MyLogger.Debug("All dictionaries converted to Diver-objects");
                return divers;
            }
            catch (Exception e)
            {
                MyLogger.Error("Could not convert all dictionaries to Diver-objects - " + e.Message);
                return null;
            }
        }

        public static void RemoveDiverFromDatabase(Diver diver)
        {
            CredentialsMap.RemoveCredentialsFromDatabase(diver.Credentials);
            foreach (var dive in diver.Dives)
                DiveMap.RemoveDiveFromDatabase(dive);
            GenericMap.RemoveObjectFromDatabase(diver);
        }

        public static Diver ReadDiverFromDatabase(int id)
        {
            var dbResult = GenericMap.ReadObjectFromDatabase(id, typeof(Diver));
            return dbResult == null ? null : Diver.GetFromDictionary(dbResult);
        }

    }
}
